package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.LogBean;
import com.project.bean.PermissionBean;
import com.project.bean.RoleBean;
import com.project.bean.UserBean;
import com.project.mapper.ILogMapper;
import com.project.mapper.IPermissionMapper;
import com.project.mapper.IRoleMapper;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private IPermissionMapper permissionMapper;
    @Autowired
    private ILogMapper logMapper;

    //根据用户名动态分页查询用户表
    @Override
    public IPage<UserBean> findByItem(Integer pageNO, String name) {
        QueryWrapper qw = new QueryWrapper();
        if (name != null && name.length() != -1) {
            qw.like("u_name", name);
        }
        qw.eq("u_status", "在职");
        return userMapper.selectPage(new Page<>(pageNO, 3), qw);
    }

    //添加用户时，用户名不能重复
    @Override
    public UserBean findByName(String name) {
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("u_name", name);
        qw.eq("u_status", "在职");
        UserBean user=userMapper.selectOne(qw);
        user=userMapper.findById(user.getId());
        if (user !=null){
            //查询角色集合
            List<RoleBean> roleList =user.getRoleList();
            //遍历角色id数组
            Integer[] roleIdArray = new Integer[user.getRoleList().size()];
            for (int i = 0; i < roleIdArray.length; i++) {
                roleIdArray[i] = roleList.get(i).getId();
            }
            //查询权限集合
            List<PermissionBean> permissionList = permissionMapper.findByRoleIdArray(roleIdArray);
            user.setPermissionList(permissionList);
            //遍历为权限id集合
            List<Integer> limitList = user.getPermissionList().stream().map(n -> n.getId()).toList();
            user.setLimitList(limitList);
        }
        return user;
    }

    //添加用户
    @Override
    public String add(UserBean user, Integer... roleIdArray) {
        //设置盐
        user.setSalt(this.getSalt());
        Md5Hash md5Hash=new Md5Hash(user.getPwd(),user.getSalt(),1024);

        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("u_name", user.getName());
        if (userMapper.selectOne(qw) == null) {
            //加密后的密码
            user.setPwd(md5Hash.toHex());
            userMapper.insert(user);
            //添加用户角色中间表
            userMapper.addRoleIdArray(user.getId(), roleIdArray);
            return "ok";
        }
        return "";
    }

    //删除用户同时删除用户拥有的角色信息，如果加一个列为状态，那么就更改状态
    //先删除中间表该用户的权限，再删除用户
    @Override
    public void del(Integer userId) {
        //删除中间表 --- 角色信息
        userMapper.delRole(userId);
        //”删除用户“
        //通过id找到用户对象
        UserBean user = userMapper.selectById(userId);
        user.setStatus("离职");
        userMapper.updateById(user);
    }

    //通过id查询用户信息，同时查询该用户拥有的角色集合，和权限集合
    @Override
    public UserBean findById(Integer id) {
        //封装角色集合
        UserBean user = userMapper.findById(id);
        Integer[] roleIdArray = new Integer[user.getRoleList().size()];
        List<RoleBean> roleList = user.getRoleList();
        for (int i = 0; i < roleIdArray.length; i++) {
            roleIdArray[i] = roleList.get(i).getId();
        }
        user.setPermissionList(permissionMapper.findByRoleIdArray(roleIdArray));
        return user;
    }

    //通过用户id修改用户的角色，先通过用户id删除中间表相关信息，再添加新的角色信息
    @Override
    public void updateRole(Integer userId, Integer... newRoleArray) {
        //删除中间表信息 -- 角色信息
        userMapper.delRole(userId);
        //添加新的中间表信息
        userMapper.addRoleIdArray(userId, newRoleArray);

    }

    @Override
    public void updatePwd(Integer userId, String newPwd) {
        UserBean user = userMapper.selectById(userId);

        Md5Hash md5Hash=new Md5Hash(newPwd,user.getSalt(),1024);
        user.setPwd(md5Hash.toHex());

        userMapper.updateById(user);
    }

    //盐
    private String getSalt() {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            int index = (int) (Math.random() * str.length());
            sb.append(str.charAt(index));
        }
        return sb.toString();
    }
}
